<template>
  <div id="app">
    <h1>用户管理系统 (Vue + Spring Boot)</h1>

    <!-- 注册表单 -->
    <div>
      <h2>注册新用户</h2>
      <input v-model="newUser.username" placeholder="Username">
      <input v-model="newUser.password" placeholder="Password" type="password">
      <input v-model="newUser.email" placeholder="Email">
      <button @click="registerUser">注册</button>
    </div>

    <hr>

    <!-- 用户列表 -->
    <div>
      <h2>用户列表</h2>
      <button @click="fetchUsers">获取用户列表</button>
      <ul>
        <li v-for="user in users" :key="user.id">
          {{ user.id }} - {{ user.username }} - {{ user.email }}
        </li>
      </ul>
    </div>

  </div>
</template>

<script>
import axios from 'axios';

// 定义 API 的基础 URL，确保它与你的后端端口一致
const API_BASE_URL = 'http://localhost:8083/api/users';

export default {
  name: 'App',
  data() {
    return {
      newUser: {
        username: '',
        password: '',
        email: ''
      },
      users: [] // 用于存储从后端获取的用户列表
    };
  },
  methods: {
    async registerUser() {
      try {
        const response = await axios.post(`${API_BASE_URL}/register`, this.newUser);
        alert(response.data.message);
        if (response.data.success) {
          // 清空表单
          this.newUser = { username: '', password: '', email: '' };
          // 重新获取用户列表
          this.fetchUsers();
        }
      } catch (error) {
        console.error('注册失败:', error);
        alert('注册失败！');
      }
    },
    async fetchUsers() {
      try {
        const response = await axios.get(API_BASE_URL);
        this.users = response.data;
      } catch (error) {
        console.error('获取用户列表失败:', error);
        alert('获取用户列表失败！');
      }
    }
  },
  // 组件挂载后自动获取用户列表
  mounted() {
    this.fetchUsers();
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
input, button {
  margin: 5px;
  padding: 8px;
}
</style>